package com.jtpay.textpay.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.jtpay.textpay.AppidDataProvider;
import com.jtpay.textpay.PayBean;
import com.jtpay.textpay.R;
import com.jtpay.textpay.adapter.PayTypeGridViewAdapter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import sdk.pay.PayUtil;
import sdk.pay.listener.PayGetPayTypeListener;
import sdk.pay.listener.PayUtilCallBack;
import sdk.pay.model.PayTypeModel;
import sdk.pay.model.TokenParam;
import sdk.pay.utils.PayMD5Util;

public class PayActivity extends Activity implements PayUtilCallBack {

    public static String APP_ID;
    public static String APP_KEY;
    public static String KEY;
    public static String VECTOR;

    protected Dialog mProgressDialog;
    private GridView mGridView;
    private TextView mPayName;
    private TextView mPayPrice;
    private PayTypeGridViewAdapter mTypeGridViewAdapter;
    private int mCheckedId = -1;
    private String mSign;
    private PayUtil mPayUtil;
    private static Activity mActivity;
    private String mOrder, mOrderTime;
    private PayBean payBean;
    private final Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            List<PayTypeModel> payTypeModelList = mPayUtil.getPayTypeModels();
            dismiss();
            if (payTypeModelList == null || payTypeModelList.size() == 0) {
                Toast.makeText(PayActivity.this, "Payment null", Toast.LENGTH_SHORT).show();
                return;
            }
            if (payTypeModelList.size() > 0) {
                mTypeGridViewAdapter.setList(payTypeModelList);
                mTypeGridViewAdapter.Portrait(isPortrait());
                mGridView.setAdapter(mTypeGridViewAdapter);
                if (mCheckedId == -1) {
                    for (PayTypeModel typeModel : payTypeModelList) {
                        if (typeModel.getTypeid().equals("ZFB")) {
                            mCheckedId = payTypeModelList.indexOf(typeModel);
                            break;
                        } else {
                            mCheckedId = 0;
                        }
                    }
                    mTypeGridViewAdapter.selectItem(mCheckedId);
                }
            } else {
                Toast.makeText(PayActivity.this, "Did not get the payment!", Toast.LENGTH_SHORT).show();
            }
            dismiss();
        }
    };
    private String goodsPrice, goodsName;
    private TokenParam tokenParam;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_layout);
        payBean = new PayBean();
        initWidgets();
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        goodsName = bundle.getString("productName");
        goodsPrice = bundle.getString("productPrice");
        APP_ID = bundle.getString("appid");
        APP_KEY = bundle.getString("appKey");
        KEY = bundle.getString("aesKey");
        VECTOR = bundle.getString("aesV");
        mTypeGridViewAdapter = new PayTypeGridViewAdapter(PayActivity.this, new ArrayList<PayTypeModel>());
        mPayUtil = new PayUtil(mActivity, this, true);
//        mPayUtil.setPayParam(APPID, KEY, VECTOR, SYSTEM_NAME);
        mPayUtil.setPayParam(APP_ID, KEY, VECTOR);
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        mOrder = mOrderTime = dateFormat.format(date);
        mProgressDialog = ProgressDialog.show(PayActivity.this, "", getString(R.string.pay_info), false, true, null);
        mPayUtil.getPayType(getTokenParam(), new PayGetPayTypeListener() {
            @Override
            public void onPayDataResult() {
                runOnUiThread(mRunnable);
            }
        });
        initView();

        /*String typeId = "WX";
        // 此mSign为支付时签名，为了安全性，建议从服务器传入
        mSign = PayMD5Util.getMD5(APP_ID + "&" + mOrder + "&" +
                goodsPrice + "&" + mOrderTime + "&" + typeId + "&" + APP_KEY);
        mPayUtil.pay(typeId, getTokenParam());*/
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setContentView(R.layout.activity_pay_layout);
        initView();
        mTypeGridViewAdapter.Portrait(isPortrait());
        mGridView.setAdapter(mTypeGridViewAdapter);
    }

    private boolean isPortrait() {
        return getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    private void initView() {
        initWidgets();
        mPayName.setText(goodsName);
        mPayPrice.setText(String.format("%s元", goodsPrice));
    }

    @Override
    protected void onResume() {
        super.onResume();
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.pay.close");
        localBroadcastManager.registerReceiver(mBroadcastReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
    }

    private TokenParam getTokenParam() {
        String p1_appid = APP_ID;
        String p2_order = mOrder;
        String p3_money = goodsPrice;
        String p6_orderTime = mOrderTime;
        tokenParam = new TokenParam();
        tokenParam.setP1_appid(p1_appid);
        tokenParam.setP2_orderNumber(p2_order);
        tokenParam.setP3_money(p3_money);
        tokenParam.setP6_orderTime(p6_orderTime);
        tokenParam.setP8_sign(mSign);
        return tokenParam;
    }

    private void initWidgets() {
        mPayName = (TextView) findViewById(R.id.junpay_TextView_name);
        mPayPrice = (TextView) findViewById(R.id.junpay_TextView_price);
        mGridView = (GridView) findViewById(R.id.junpay_gridview);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mCheckedId = position;
                mTypeGridViewAdapter.selectItem(mCheckedId);
            }
        });

        findViewById(R.id.junpay_button_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCheckedId >= 0) {
                    mProgressDialog = ProgressDialog.show(PayActivity.this, "", getString(R.string.pay_info), false, true, null);
                    String typeId = getTypeId(mCheckedId);
                    // 此mSign为支付时签名，为了安全性，建议从服务器传入
                    mSign = PayMD5Util.getMD5(APP_ID + "&" + mOrder + "&" +
                            goodsPrice + "&" + mOrderTime + "&" + typeId + "&" + APP_KEY);
                    mPayUtil.pay(typeId, getTokenParam());
                    AppidDataProvider.insertDb(APP_ID, APP_KEY, KEY, VECTOR, PayActivity.this);

                } else {
                    Toast.makeText(PayActivity.this, "Payment has not yet chosen", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public static void startActivity(Activity activity, String productName, String productPrice, String appid, String appKey, String aesKey, String aesV) {
        Intent intent = new Intent(activity, PayActivity.class);
        mActivity = activity;
        intent.putExtra("productName", productName);
        intent.putExtra("productPrice", productPrice);
        intent.putExtra("appid", appid);
        intent.putExtra("appKey", appKey);
        intent.putExtra("aesKey", aesKey);
        intent.putExtra("aesV", aesV);
        activity.startActivity(intent);
    }

    private void dismiss() {
        if (null != mProgressDialog && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private String getTypeId(int index) {
        List<PayTypeModel> list = mPayUtil.getPayTypeModels();
        PayTypeModel model = list.get(index);
        return model.getTypeid();
    }

    @Override
    public void onPayException(String exceptionMessage) {
        dismiss();
        mActivity = null;
        finish();
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };

}